import { createReadStream, readdirSync } from 'fs';
import { red } from 'kolorist';
import { extname, resolve } from 'path';
import { IMessage } from 'qq-guild-bot';
import readline from 'readline';

const _path = process.cwd();

export function prohibited(e: { msg: IMessage; eventType: string }) {
  if (
    e.msg.content &&
    e.eventType === 'MESSAGE_CREATE' &&
    e.msg.content.indexOf('/违禁词添加') === -1 &&
    e.msg.content.indexOf('/违禁词删除') === -1
  ) {
    // 1	全体成员
    // 2	管理员
    // 4	群主/创建者
    // 5	子频道管理员
    if (
      e.msg.member.roles.includes('2') ||
      e.msg.member.roles.includes('4') ||
      e.msg.member.roles.includes('5')
    ) {
      return;
    }

    const files = readdirSync(resolve(_path, './plugins/违禁词/resources/prohibited/'));

    try {
      files.forEach(file => {
        if (extname(file) === '.txt') {
          let rl = readline.createInterface({
            input: createReadStream(resolve(_path, './plugins/违禁词/resources/prohibited/', file))
          });
          let exist = [];
          rl.on('line', line => {
            if (line && line.trim() !== '') {
              if (e.msg.content.indexOf(line) !== -1) {
                // @ts-ignore
                exist.push(line);
              }
            }
          });
          rl.on('close', () => {
            if (exist.length > 0) {
              //  撤回消息
              client.messageApi
                .deleteMessage(e.msg.channel_id, e.msg.id, false)
                .then(res => {
                  // 禁言
                  client.muteApi
                    .muteMember(e.msg.guild_id, e.msg.author.id, {
                      seconds: 5 * 60 + '' // 5分钟
                    })
                    .then(res => {
                      // 发警告
                      let message = {
                        content: `<@!${e.msg.author.id}> 请文明用语`
                      };
                      client.messageApi.postMessage(e.msg.channel_id, message).catch(err => {
                        console.error(red(JSON.stringify(err, null, 2)));
                      });
                    })
                    .catch(err => {
                      console.error(red(JSON.stringify(err, null, 2)));
                    });
                })
                .catch(err => {
                  // 机器人权限不足，无法删除消息
                  console.error(red('[违禁词]: 机器人权限不足，无法删除消息'));
                  console.error(red(JSON.stringify(err, null, 2)));
                });

              return true;
            }
          });
        }
      });
    } catch (e) {
      console.error(red(JSON.stringify(e, null, 2)));
    }
  }
}
